// pages/user_center/travelagency/bill/bill.js
var util = require('../../../../utils/util.js');
var Tool = require("../../../../utils/ztool.js");
var tool = new Tool();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    usertype: '',
    selectcarcomp: 1,
    selectguide: 0,
    selectdriver: 0,
    selectpassenger: 0,
    startdate: '2018-01-01',
    enddate: '2018-01-31',
    isselect: false,
    allCompBill: [],//头
    singleCompBill: [],//月
    spareallCompBill: [],//
    sparesingleCompBill: [],//
    searchkey: '',

    scrollTop: 0,
    viewheight: '',
    nodate: false,

    // 公司查看司机列表
    com2driver: false,
    //车公司查看用车方
    com2com: false,

    //司机查看公司
    drivertoCom: false,
    //导游查看公司
    GuidertoCom: false,

    gsArr: [],

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    var useinfo = wx.getStorageSync('userInfo');
    console.log(useinfo)
    this.setData({
      
      usertype: useinfo.USerType,
      viewheight: wx.getSystemInfoSync().windowHeight - 44
    })

    this.chooseInterface()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.chooseInterface()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.usertype == '3' || this.data.usertype == '4') {
      wx.showToast({
        title: '没有更多数据',
        icon: 'none',
        duration: 2000
      })
      return;
    }


    var test = this.data.spareallCompBill
    if (test.length <= 20) {
      console.log('没有数据了 不做切割操作')
      wx.showToast({
        title: '没有更多数据',
        icon: 'none',
        duration: 2000
      })
      return
    }

    this.setData({
      allCompBill: []
    });

    wx.showLoading({
      title: '加载中',
      duration: 1500
    })

    this.setData({
      allCompBill: this.data.allCompBill.concat(test.splice(0, 20)),
    });

    wx.pageScrollTo({
      scrollTop: 0
    })
  },

  chooseInterface: function () {
    var that = this
    var url = ''
    var act1 = ''
    var act2 = ''
    console.log('chooseInterface')
    console.log(that.data.usertype)
    // this.setData({
    //   allCompBill: [],
    //   singleCompBill: [],
    // })

    that.setData({
      com2com: false,
      com2driver: false,
      nodate: false,
    })

    switch (that.data.usertype) {
      case '1':
        console.log('车公司')
        if (that.data.selectcarcomp == 1) {
          url = 'https://www.lanshuicar.com/Server/ComputeTotal/CgsComTotalHdl.ashx'
          act1 = 'getAllComTotal'
          act2 = 'getSingComTotal'
          that.setData({
            com2com: true
          })
          that.getBillTotal(url, act1, act2)
        } else if (that.data.selectdriver == 1) {
          url = 'https://www.lanshuicar.com/Server/ComputeTotal/CgsSjTotalHdl.ashx'
          act1 = 'getAllDriverTotal'
          that.setData({
            com2driver: true
          })
          that.getBillTotal2(url, act1, act2)
        }
        break
      case '2':
        console.log('用车方')
        if (that.data.selectcarcomp == 1) {
          url = 'https://www.lanshuicar.com/Server/ComputeTotal/LxsComTotalHdl.ashx'
          act1 = 'getAllComTotal'
          act2 = 'getSingComTotal'
          that.setData({
            com2com: true
          })
          that.getBillTotal(url, act1, act2)
        } else if (that.data.selectdriver == 1) {
          url = 'https://www.lanshuicar.com/Server/ComputeTotal/LxsSjTotalHdl.ashx'
          act1 = 'getAllDriverTotal'
          that.setData({
            com2driver: true
          })
          that.getBillTotal2(url, act1, act2)
        } else if (that.data.selectguide == 1) {
          url = 'https://www.lanshuicar.com/Server/ComputeTotal/LxsDyTotalHdl.ashx'
          act1 = 'getAllGuiderTotal'
          that.setData({
            com2driver: true
          })
          that.getBillTotal2(url, act1, act2)
        }
        break
      case '3':
        console.log('司机')
        that.setData({
          drivertoCom: true
        })
        url = 'https://www.lanshuicar.com/Server/ComputeTotal/SjComTotalHdl.ashx'
        that.getBillTotal(url, 'getAllOrders', '')
        break
      case '4':
        console.log('导游')
        that.setData({
          GuidertoCom: true
        })

        url = 'https://www.lanshuicar.com/Server/ComputeTotal/DyComTotalHdl.ashx'
        that.getBillTotal(url, 'getAllOrders', '')
        break
    }
  },

  /**
   * 获取各个公司汇总统计
   */
  getBillTotal: function (url, act1, act2) {
    var that = this
    var useinfo = wx.getStorageSync('userInfo');
    console.log(useinfo);
    var pwd = wx.getStorageSync('password');
    that.data.allCompBill = []
    console.log(that.data.allCompBill.length)
    var tel = ''
    if (that.data.usertype == '1' || that.data.usertype == '2') {
      tel = useinfo.Telphone
    }
    if (that.data.usertype == '3' || that.data.usertype == '4') {
      tel = useinfo.sTel
    }

    console.log(tel)
    wx.request({
      url: url,
      data: {
        tel: tel,
        pwd: pwd,
        dates: that.data.startdate,
        datee: that.data.enddate,
        act: act1,
        comname: that.data.searchkey
      },
      method: 'GET',
      success: function (res) {
        if (res.statusCode == 404) {
          //接口加载失败
          console.log('加载接口错误');
          //显示错误信息
          that.showError('订单信息接口请求失败')
          that.setData({
            loadError: true
          });
          return
        }

        var data = tool.getRegularJson(res.data);
        console.log(data)

        if (data.code != 0) {
          that.showError(data.msg)
          return
        }


        if (data.data.length > 0) {
          that.data.spareallCompBill = data.data
          // console.log(that.data.spareallCompBill.length)
          if (act2 == '') {
            // that.setData({
            //   allCompBill: data.data
            // })
            that.data.allCompBill = data.data
            if (that.data.usertype == "3") {
              that.dealDriverData()
            }
            if (that.data.usertype == "4") {
              that.dealGuiderData()
            }
          } else {
            that.setData({
              allCompBill: data.data.splice(0, 20),
              singleCompBill: []
            });
          }
          console.log(that.data.allCompBill.length)
          // console.log(that.data.spareallCompBill.length)

          //停止下拉刷新动画
          wx.stopPullDownRefresh();
          console.log(that.data.allCompBill)
          if (act2 != '') {
            that.getSingBill(url, act2)

          }
          // else{
          // that.dealDriverGuiderData()
          // }

          // if (that.data.spareallCompBill.length == 0) {
          that.setData({
            nodate: false
          });
          // }
          console.log('#1')
        } else {
          that.setData({
            nodate: true,
            allCompBill: [],
            spareallCompBill: [],
            gsArr: [],
          });
          console.log('#2')
        }
      },
      fail: function () {
        console.log('加载错误');
        that.setData({
          loadError: true
        });

      }
    })
  },

  dealDriverData: function () {
    var data = this.data.allCompBill
    var gsName = []
    for (var i = 0; i < data.length; i++) {
      if (data[i].cgsName == "") {
        if (gsName.indexOf(data[i].lxsName) == -1) {
          gsName.push(data[i].lxsName)

        }
      } else {
        if (gsName.indexOf(data[i].cgsName) == -1) {
          gsName.push(data[i].cgsName)

        }
      }
    }
    var arrNew = []
    for (var k in gsName) {
      var arr = []
      var total = 0
      for (var i = 0; i < data.length; i++) {
        if (data[i].cgsName == "") {
          if (gsName[k] == data[i].lxsName) {
            var routeTitle = data[i].routeTitle
            if (routeTitle == "(null)") {
              routeTitle = ""
            }
            var obj = {
              "name": data[i].lxsName,
              "routeTitle": routeTitle,
              "tMony": data[i].tMony,
              "oDate": data[i].oDate,
              "total": data[i].tMony
            }
            total = total + parseInt(obj.total)
            obj.total = total
            arr.push(obj)
          }
        } else {
          if (gsName[k] == data[i].cgsName) {
            var routeTitle = data[i].routeTitle
            if (routeTitle == "(null)") {
              routeTitle = ""
            }
            var obj = {
              "name": data[i].cgsName,
              "routeTitle": routeTitle,
              "tMony": data[i].tMony,
              "oDate": data[i].oDate,
              "total": data[i].tMony
            }
            total = total + parseInt(obj.total)
            obj.total = total
            arr.push(obj)
          }
        }
      }
      arrNew.push(arr)
    }


    this.setData({
      gsArr: arrNew
    })

    console.log("33#")
    console.log(arrNew)
  },

  dealGuiderData: function () {
    var data = this.data.allCompBill
    var gsName = []
    for (var i = 0; i < data.length; i++) {
      if (gsName.indexOf(data[i].lxsName) == -1) {
        gsName.push(data[i].lxsName)
      }
    }

    var arrNew = []
    for (var k in gsName) {
      var arr = []
      var total = 0
      for (var i = 0; i < data.length; i++) {
        if (gsName[k] == data[i].lxsName) {
          var routeTitle = data[i].routeTitle
          if (routeTitle == "(null)") {
            routeTitle = ""
          }
          var obj = {
            "name": data[i].lxsName,
            "routeTitle": routeTitle,
            "tMony": data[i].tMony,
            "oDate": data[i].oDate,
            "total": data[i].tMony
          }
          total = total + parseInt(obj.total)
          obj.total = total
          arr.push(obj)
        }
      }
      arrNew.push(arr)
    }


    this.setData({
      gsArr: arrNew
    })

    console.log(arrNew)

  },


  getBillTotal2: function (url, act1, act2) {
    var that = this
    var useinfo = wx.getStorageSync('userInfo');
    console.log(useinfo);
    var pwd = wx.getStorageSync('password');
    that.data.allCompBill = []
    that.data.spareallCompBill = []
    console.log(that.data.allCompBill.length)
    var tel = ''
    if (that.data.usertype == '1' || that.data.usertype == '2') {
      tel = useinfo.Telphone
    }
    if (that.data.usertype == '3' || that.data.usertype == '4') {
      tel = useinfo.sTel
    }

    console.log(tel)
    wx.request({
      url: url,
      data: {
        tel: tel,
        pwd: pwd,
        dates: that.data.startdate,
        datee: that.data.enddate,
        act: act1,
        sname: that.data.searchkey,
      },
      method: 'GET',
      success: function (res) {
        if (res.statusCode == 404) {
          //接口加载失败
          console.log('加载接口错误');
          //显示错误信息
          that.showError('订单信息接口请求失败')
          that.setData({
            loadError: true
          });
          return
        }

        var data = tool.getRegularJson(res.data);
        console.log(data)

        if (data.code != 0) {
          that.showError(data.msg)
          return
        }


        if (data.data.length > 0) {
          // that.data.spareallCompBill = data.data
          // console.log(that.data.spareallCompBill.length)
          if (act2 == '') {
            that.data.allCompBill = data.data
            var array = []
            //将stel为空的剔除
            for (var i in that.data.allCompBill) {
              if (that.data.allCompBill[i].partTel) {
                array.push(that.data.allCompBill[i])
              }
            }
            //赋值渲染
            that.setData({
              allCompBill: array
            })
          } else {
            that.setData({
              allCompBill: data.data.splice(0, 20),
              singleCompBill: []
            });
          }
          console.log(that.data.allCompBill.length)
          // console.log(that.data.spareallCompBill.length)

          //停止下拉刷新动画
          wx.stopPullDownRefresh();
          console.log(that.data.allCompBill)
          if (act2 != '') {
            that.getSingBill(url, act2)

          }
          // else{
          // that.dealDriverGuiderData()
          // }

          // if (that.data.spareallCompBill.length == 0) {
          that.setData({
            nodate: false
          });
          // }
          // console.log('#1')
        } else {
          that.setData({
            nodate: true,
            allCompBill: [],
            spareallCompBill: [],
          });
          // console.log('#2')
        }
      },
      fail: function () {
        console.log('加载错误');
        that.setData({
          loadError: true
        });

      }
    })
  },

  getSingBill: function (url, act2) {
    var that = this
    var useinfo = wx.getStorageSync('userInfo');
    var pwd = wx.getStorageSync('password');
    that.data.singleCompBill = []
    console.log(useinfo)
    console.log(pwd)
    wx.request({
      url: url,
      data: {
        tel: useinfo.Telphone,
        pwd: pwd,
        dates: that.data.startdate,
        datee: that.data.enddate,
        act: act2,
        comname: that.data.searchkey
      },
      method: 'GET',
      success: function (res) {
        if (res.statusCode == 404) {
          //接口加载失败
          console.log('加载接口错误');
          //显示错误信息
          that.showError('订单信息接口请求失败')
          that.setData({
            loadError: true
          });
          return
        }

        var data = tool.getRegularJson(res.data);
        console.log(data)

        if (data.code != 0) {
          that.showError(data.msg)
        }

        if (data.data.length > 0) {
          that.setData({
            singleCompBill: that.data.singleCompBill.concat(data.data)
          });
          console.log(that.data.singleCompBill)
        }
      },
      fail: function () {
        console.log('加载错误');
        that.setData({
          loadError: true
        });

      }
    })
  },

  godetail: function () {
    wx.navigateTo({
      url: '../../travelagency/bill/billdetail',
    })
  },

  SelectCarComp: function () {
    this.setData({
      selectcarcomp: 1,
      selectguide: 0,
      selectdriver: 0,
      selectpassenger: 0,
      allCompBill: [],
    })
    this.chooseInterface()
  },

  SelectGuide: function () {
    this.setData({
      selectcarcomp: 0,
      selectguide: 1,
      selectdriver: 0,
      selectpassenger: 0,
      allCompBill: [],
    })
    this.chooseInterface()
  },

  SelectDriver: function () {
    this.setData({
      selectcarcomp: 0,
      selectguide: 0,
      selectdriver: 1,
      selectpassenger: 0,
      allCompBill: [],
    })
    this.chooseInterface()
  },

  SelectPassenger: function () {
    this.setData({
      selectcarcomp: 0,
      selectguide: 0,
      selectdriver: 0,
      selectpassenger: 1,
      allCompBill: [],
    })
  },

  changeselect: function () {
    if (this.data.isselect) {
      this.setData({
        isselect: false,
      })
    } else {
      this.setData({
        isselect: true,
      })
    }
  },

  bindStartDateChange: function (e) {
    console.log(e)
    this.setData({
      startdate: e.detail.value,
    })
  },

  bindEndDateChange: function (e) {
    console.log(e)
    this.setData({
      enddate: e.detail.value,
    })
  },

  cleandate: function () {
    var time1 = util.formatTime1(new Date());
    this.setData({
      startdate: '2018-01-01',
      enddate: time1,
      searchkey: '',
    })
  },

  search: function () {
    this.setData({
      isselect: false,
    })

    this.chooseInterface()
  },

  inputSearchKey: function (e) {
    console.log(e)
    this.setData({
      searchkey: e.detail.value
    })
  },

  showError: function (msg) {
    var that = this;
    that.setData({
      formError: true,
      errorMessage: msg
    });

    setTimeout(function () {
      that.setData({
        formError: false,
        errorMessage: '未知错误'
      });
    }, 2000);
  },
  //处理数据
  // dealDriverGuiderData:function(){
  //   var obj = {
  //     gsName:'',
  //     tel:'',
  //     Totalorder:0,
  //     TotalMoney:0,

  //   }
  //   that.data.allCompBill
  // },
  //月详单
  monthdetail: function (e) {
    var type = ''
    //选择了旅行社或车公司
    if (this.data.selectcarcomp == 1) {
      type = 2
      var comname = e.currentTarget.dataset.comname
      //车公司<=>旅行社
      if (this.data.usertype == 1 || this.data.usertype == 2) {
        var date = e.currentTarget.dataset.date
        var datestart = date + '-01'
        var nextmonthdate = getNextMonth(datestart)
        var dateend = getDateStr(nextmonthdate)
        wx.navigateTo({
          url: 'billdetail?datestart=' + datestart + '&dateend=' + dateend + '&type=' + type + '&comname=' + comname,
        })
      }
    }
    //选择了司机
    if (this.data.selectdriver == 1) {
      type = 3
      var stel = e.currentTarget.dataset.stel
      var sjname = e.currentTarget.dataset.sjname
      //车公司对司机
      if (this.data.usertype == 1 || this.data.usertype == 2) {
        wx.navigateTo({
          url: 'billdetail?datestart=' + this.data.startdate + '&dateend=' + this.data.enddate + '&type=' + type + '&stel=' + stel + '&sjname=' + sjname,
        })
      }

    }

    //选择了导游
    if (this.data.selectguide == 1) {
      type = 4
      var stel = e.currentTarget.dataset.stel
      var sjname = e.currentTarget.dataset.sjname
      //旅行社对导游
      if (this.data.usertype == 2) {
        wx.navigateTo({
          url: 'billdetail?datestart=' + this.data.startdate + '&dateend=' + this.data.enddate + '&type=' + type + '&stel=' + stel + '&sjname=' + sjname,
        })
      }
    }




  },



})
//获取后一个月
function getNextMonth(date) {
  var arr = date.split('-');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var day = arr[2]; //获取当前日期的日
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中的月的天数
  var year2 = year;
  var month2 = parseInt(month) + 1;
  if (month2 == 13) {
    year2 = parseInt(year2) + 1;
    month2 = 1;
  }
  var day2 = day;
  var days2 = new Date(year2, month2, 0);
  days2 = days2.getDate();
  if (day2 > days2) {
    day2 = days2;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }
  var t2 = year2 + '-' + month2 + '-' + day2;
  return t2;
}
//获取前一天
function getDateStr(today) {
  var dd;
  if (today) {
    dd = new Date(today);
  } else {
    dd = new Date();
  }
  dd.setDate(dd.getDate() - 1);//获取AddDayCount天后的日期 
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1;//获取当前月份的日期 
  var d = dd.getDate();
  if (m < 10) {
    m = '0' + m;
  };
  if (d < 10) {
    d = '0' + d;
  };
  return y + "-" + m + "-" + d;
}
